﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Spore.Validator
{
    /// <summary>
    /// 字符长度验证器
    /// </summary>
   public class ValidatorLength:ValidatorBase
    {
        /// <summary>
        /// 最小长度
        /// </summary>
        private int mMinLength;
        /// <summary>
        /// 最大长度
        /// </summary>
        private int mMaxLength;

        /// <summary>        
        /// </summary>
        /// <param name="minLen">长度下限</param>
        /// <param name="maxLen">长度上限</param>
        /// <param name="errMsg">验证未通过时错误提示信息</param>
        public ValidatorLength(int minLen, int maxLen, string errMsg)
            : base(errMsg)
        {
            if (minLen < 0)
            {
                throw new ArgumentOutOfRangeException("字段长度不能为负");
            }
            if (minLen > maxLen)
            {
                throw new ArgumentException("最大长度不能小于最下长度");
            }
            mMinLength = minLen;
            mMaxLength = maxLen;
        }

       /// <summary>
       /// 
       /// </summary>
        /// <param name="minLen">长度下限</param>
        /// <param name="maxLen">长度上限</param>
        public ValidatorLength(int minLen, int maxLen)
        {
            if (minLen < 0)
            {
                throw new ArgumentOutOfRangeException("字段长度不能为负");
            }
            if (minLen > maxLen)
            {
                throw new ArgumentException("最大长度不能小于最下长度");
            }
            mMinLength = minLen;
            mMaxLength = maxLen;
            this.ErrorMessage = string.Format("输入值的长度小于{0}或大于{1}",this.mMinLength.ToString(),this.mMaxLength.ToString());
        }

        /// <summary>
        /// 验证控件内容是否在指定长度范围内
        /// </summary>
        /// <param name="controlToValidate">待验证控件</param>
        /// <returns>如果在范围内,返回true;否则返回false</returns>
        public override bool IsValid(Control controlToValidate)
        {
            if (this.mMinLength > 0)
            {
                if (controlToValidate.Text == null)
                    return false;
                else
                {
                    if ((controlToValidate.Text.Trim().Length >= mMinLength) && (controlToValidate.Text.Trim().Length <= mMaxLength))
                    {
                        return true;
                    }
                    return false;
                }
            }
            else
            {
                if (controlToValidate.Text == null)
                    return true;
                if ((controlToValidate.Text.Trim().Length >= mMinLength) && (controlToValidate.Text.Trim().Length <= mMaxLength))
                {
                    return true;
                }
            }
            return false;
        }


    }
}
